import { useMutation, useQuery } from "@tanstack/react-query";
import { message, Modal, Tree } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react"
import { appModelApi, appModelShowApi, permissionListTree, findAppClassify } from '@/api/system/role'


const filterOptions = (list) => {
  return list.map(item => {
    if (item.isExistMenu === '0') {
      item.disabled = true
    }
    if (item.appChildren && item.appChildren.length) {
      filterOptions(item.appChildren)
    }
    return item
  })
}



const RoleAppModal = forwardRef((props, ref) => {
  const [roleId, setRoleId] = useState()
  const [checkedKeys, setCheckedKeys] = useState([])
  const [permissionAll, setPermissionAll] = useState([])
  const [isModalOpen, setIsModalOpen] = useState()
  const { data: treeOptions, isRefetching, error } = useQuery({
    queryKey: ['roleAppList', roleId],
    queryFn: () => {
      return permissionListTree({ roleId: roleId }).then(({ data = [] }) => {
        setCheckedKeys(traverseTree(data))
        return data.map(d => {
          if (d.name === '统一认证后台') {
            d.disabled = true
          }
          return d
        })
      })
      // return findAppClassify({ roleId: roleId }).then(({ data = [] }) => {
      //   return filterOptions(data.map((d, i) => ({ ...d, id: d.appType + i })))
      // })
    },
    staleTime: 0,
    enabled: !!roleId
  })

  useImperativeHandle(ref, () => ({
    showModal: (id) => {
      setRoleId(id)
      setIsModalOpen(true)
    },
  }));

  const mutation = useMutation({
    mutationFn: (param) => {
      return appModelApi(param)
    },
    onSuccess: (res) => {
      if (res.code === 200) {
        setIsModalOpen(false)
        message.success('操作成功')
      }
    }
  })

  const handleOk = () => {
    // let checked = []
    // permissionAll.forEach(item => {
    //   if (checkedKeys.includes(item.id)) {
    //     checked.push(item)
    //   }
    // })

    mutation.mutate({ resourceIds: checkedKeys, roleId })
  };
  const handleCancel = () => {
    setIsModalOpen(false)
  };
  // 获取数据遍历树，如子集未勾选全去掉父级勾选

  const traverseTree = (arr, result = []) => {
    arr.forEach(obj => {
      if (obj.children && obj.children.length) {
        if (obj.isChecked === '1' && !obj.children.find(d => d.isChecked === '0')) {
          result.push(obj.id)
        }
        traverseTree(obj.children, result)
      } else if (obj.isChecked === '1') {
        result.push(obj.id)
      }
    })
    return result
  }
  return <Modal loading={isRefetching} title="权限管理" open={isModalOpen} confirmLoading={mutation.isPending} onOk={handleOk} onCancel={handleCancel}>
    <Tree
      checkable
      checkedKeys={checkedKeys}
      autoExpandParent={true}
      fieldNames={{ title: 'name', children: 'children', key: 'id' }}
      treeData={treeOptions}
      onCheck={(val) => {
        setCheckedKeys(val)
      }}
    ></Tree>
  </Modal>
})

export default RoleAppModal